﻿using Infrastructure;
using Senparc.Weixin;
using Senparc.Weixin.Exceptions;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WsdShop.IService;
using WsdShop.Model;
using WsdShop.Model.Enum;
using Infrastructure.Tool;
using Infrastructure.Pub;
using SqlSugar;
using Senparc.Weixin.MP.Helpers;
using WsdShop.IService.Common;

namespace WeChat.Controllers
{
    public class WxController : Controller
    {
        private string appId;
        private string secret;
        private string checkUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={0}";

        private IMemberService _memberService;
        private IWxConfigService configservice;
        private ILogService logService;

        public WxController(IMemberService memberService, IWxConfigService _configservice,ILogService l)
        {
            _memberService = memberService;
            configservice = _configservice;
            logService = l;

            var config = configservice.GetConfig();
            appId = config.AppId;
            secret = config.AppSecret;
        }

        public ActionResult Index(string returnUrl)
        {
            var state = "JeffreySu-" + DateTime.Now.Millisecond;//随机数，用于识别请求可靠性
            Session["State"] = state;//储存随机数到Session
            if (!string.IsNullOrWhiteSpace(returnUrl) && returnUrl != "undefined")
            {
                Session["ReturnUrl"] = returnUrl;
            }
            else
            {
                Session["ReturnUrl`1"] = "";
            }


            //此页面引导用户点击授权
            string url=OAuthApi.GetAuthorizeUrl(appId,
            "http://" + Request.UrlReferrer.Host + "/Wx/Callback",
            state, OAuthScope.snsapi_userinfo);

            ViewBag.Url = url;
            return View();
        }

        //public ActionResult Callback(string code, string state)
        //{
        //    if (string.IsNullOrEmpty(code))
        //    {
        //        return Content("您拒绝了授权！");
        //    }

        //    OAuthAccessTokenResult result = null;

        //    //通过，用code换取access_token
        //    try
        //    {
        //        result = OAuthApi.GetAccessToken(appId, secret, code);
        //    }
        //    catch (Exception ex)
        //    {
        //        return Content(ex.Message);
        //    }
        //    if (result.errcode != ReturnCode.请求成功)
        //    {
        //        return Content("错误：" + result.errmsg);
        //    }
        //    //下面2个数据也可以自己封装成一个类，储存在数据库中（建议结合缓存）
        //    //如果可以确保安全，可以将access_token存入用户的cookie中，每一个人的access_token是不一样的
        //    Session["OAuthAccessTokenStartTime"] = DateTime.Now;
        //    Session["OAuthAccessToken"] = result;

        //    //因为第一步选择的是OAuthScope.snsapi_userinfo，这里可以进一步获取用户详细信息
        //    try
        //    {


        //        OAuthUserInfo userInfo = OAuthApi.GetUserInfo(result.access_token, result.openid);
        //        var member = _memberService.GetMemberInfo("OpenId='" + result.openid + "'");
        //        if (member == null)
        //        {
        //            member = new Member();
        //            member.NickName = userInfo.nickname;
        //            member.Avatar = userInfo.headimgurl;
        //            member.Sex = (SexEnum)userInfo.sex;
        //            member.AddUserId = 0;
        //            member.MemberLevel = 1;
        //            member.Balance = 0;
        //            member.TotalPay = 0;
        //            member.Status = UserStateEnum.正常;
        //            member.Points = 0;
        //            member.OpenId = result.openid;
        //            int mid = _memberService.AddMember(member);

        //            member = _memberService.GetMemberInfo(mid);
        //        }

        //        Generator.SetCookie(PubConst.CookieMemberKey, member.Id.ToString());



        //        CacheManager<Member>.GetInstance().Add(PubGet.GetMemberKey, member, int.MaxValue);



        //        string returnUrl = "http://wx.youpinsanyue.com/#/shop/";

        //        if (Session["ReturnUrl"] != null && !string.IsNullOrWhiteSpace(Session["ReturnUrl"].ToString()))
        //        {
        //            returnUrl = Session["ReturnUrl"].ToString();
        //        }
        //        ViewBag.Return = returnUrl;
        //        return View();
        //    }
        //    catch (ErrorJsonResultException ex)
        //    {
        //        return Content(ex.Message);
        //    }
        //}


        public ActionResult Callback(string code, string state, string returnUrl)
        {
            //因为第一步选择的是OAuthScope.snsapi_userinfo，这里可以进一步获取用户详细信息
            try
            {
                //测试信息
                OAuthUserInfo userInfo = new OAuthUserInfo();
                userInfo.openid = "oFbCwt5DxDDRah-0cr73FjWZaS-E";
                userInfo.sex = 1;
                userInfo.nickname = "雪诺123";
                userInfo.headimgurl = "http://wx.qlogo.cn/mmopen/AxZybNvEo1OCb5USpZR3zfs59LGTIFsxsxV7P8asBXP99Svkh30WlO3VqECDqibuXRz1EvcQiasibws6VFTcK0ibWu93OvoEicLpj/0";

                var member = _memberService.GetMemberInfo("OpenId='" + userInfo.openid + "'");
                if (member == null)
                {
                    member = new Member();
                    member.NickName = userInfo.nickname;
                    member.Avatar = userInfo.headimgurl;
                    member.Sex = (SexEnum)userInfo.sex;
                    member.AddUserId = 0;
                    member.MemberLevel = 1;
                    member.Balance = 0;
                    member.TotalPay = 0;
                    member.Status = UserStateEnum.正常;
                    member.Points = 0;
                    member.OpenId = userInfo.openid;
                    int mid = _memberService.AddMember(member);

                    member = _memberService.GetMemberInfo(mid);
                }

                Generator.SetCookie(PubConst.CookieMemberKey, member.Id.ToString());



                CacheManager<Member>.GetInstance().Add(string.Format(PubConst.CacheMemberKey, member.Id.ToString()), member, int.MaxValue);

                if (string.IsNullOrWhiteSpace(returnUrl))
                {
                    returnUrl = "/#/shop";
                }

                if (Session["ReturnUrl"] != null && !string.IsNullOrWhiteSpace(Session["ReturnUrl"].ToString()))
                {
                    returnUrl = Session["ReturnUrl"].ToString();
                }
                ViewBag.Return = returnUrl;

                return View();

            }
            catch (ErrorJsonResultException ex)
            {
                return Content(ex.Message);
            }
        }


        [HttpPost]
        public ActionResult JsSdkConfig(string url)
        {
            try
            {
                url = HttpUtility.UrlDecode(url);
                string token = configservice.GetCurrentToken(checkUrl, appId, secret);
                var config = JSSDKHelper.GetJsSdkUiPackageByToken(token, appId, secret, url);
                return Json(new
                {
                    appid = config.AppId,
                    timestamp = config.Timestamp,
                    nonceStr = config.NonceStr,
                    signature = config.Signature,
                    jsApiList = new string[]
                        {
                        "checkJsApi", "onMenuShareTimeline", "onMenuShareAppMessage", "onMenuShareQQ",
                        "onMenuShareWeibo", "uploadImage", "chooseImage","scanQRCode"
                        }
                });
            }
            catch(Exception ex)
            {
                logService.OperationLog(111, "wegaeg", Request.RawUrl,
                            "获取JSSDK失败", ex.Message, Generator.GetIP());
                return Json(ex.Message);
            }
        }

        [HttpPost]
        public ActionResult GetAppSetting()
        {
            return Json(new { ImgUploadUrl = WsdConfig.GetAppString("ImgUploadUrl"), ImgHostUrl = WsdConfig.GetAppString("ImgHostUrl") });
        }

    }
}